﻿using WCS.Infrastructure.Tools;
using WCS.Service.Interface;
using System.Text;

namespace WCS.Api.Admin.MiddleWares
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionMiddle
    {
        private readonly IConfiguration _configuration;
        private readonly RequestDelegate _next;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="next"></param>
        public ExceptionMiddle(IConfiguration configuration, RequestDelegate next)
        {

            _configuration = configuration;
            _next = next;
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="logService"></param>
        /// <param name="userService"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context, ILogService logService, IUserService userService)
        {

            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {

                var user = await userService.GetUserByCodeAsync(context.Response.HttpContext.User.Identity?.Name);
                string? userId = context.GetCurrentUserId();

                string paras = "";

                if (context.Request.Method.ToUpper() == "GET")
                {
                    var keys = context.Request.Query.Keys;
                    foreach (var item in keys)
                    {
                        paras += $"{item}={context.Request.Query[item]};";
                    }
                }
                else
                {

                    var request = context.Request;
                    //启动倒带方式
                    request.EnableBuffering();
                    if (request.Method.ToLower().Equals("post"))
                    {
                        request.Body.Seek(0, SeekOrigin.Begin);
                        using var reader = new StreamReader(request.Body, Encoding.UTF8);
                        paras = await reader.ReadToEndAsync();
                        //paras = paras.Length > 999 ? paras.Substring(0, 999) : paras;
                    }
                }

                //var errorMessage = ex.Message;
                try
                {
                    string path = _configuration["Path:Logs"];
                    string name = DateTime.Now.ToString("yyyyMMdd") + "_error.txt";
                    string content = "";
                    content += "时间：" + DateTime.Now.ToString() + "\r\n";
                    content += "url：" + context.Request.Path + "\r\n";
                    content += "method：" + context.Request.Method + "\r\n";
                    content += "参数：" + paras + "\r\n";
                    content += "用户：" + userId + "\r\n";
                    content += "错误信息：" + ex + "\r\n----------------------------------------------\r\n\r\n";
                    System.IO.File.AppendAllText(path + name, content);
                }
                catch (Exception exc)
                {

                }

                try
                {
                    await logService.WriteError(new Infrastructure.EFCore.ErrorLog
                    {
                        Id = Config.GUID(),
                        Api = context.Request.Path,
                        CreationTime = DateTime.Now,
                        Ip = Config.GetIp(),
                        Message = ex.Message,
                        Params = paras,
                        UserId = userId,
                    });
                }
                catch (Exception exce)
                {

                }

                // 设置HTTP状态码为500
                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json";

                await context.Response.WriteAsJsonAsync(new
                {
                    code = -500,
                    message = $"程序出现错误，详情查看错误日志:{(ex.Message)}"
                });
            }


        }

    }
}
